home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / share / perl5 / HTML / Form.pm < prev    next >
Encoding:
Perl POD Document  |  2008-10-20  |  34.3 KB  |  1,449 lines

  1. package HTML::Form;
  2.  
  3. use strict;
  4. use URI;
  5. use Carp ();
  6.  
  7. use vars qw($VERSION);
  8. $VERSION = "5.817";
  9.  
  10. my %form_tags = map {$_ => 1} qw(input textarea button select option);
  11.  
  12. my %type2class = (
  13.  text     => "TextInput",
  14.  password => "TextInput",
  15.  hidden   => "TextInput",
  16.  textarea => "TextInput",
  17.  
  18.  "reset"  => "IgnoreInput",
  19.  
  20.  radio    => "ListInput",
  21.  checkbox => "ListInput",
  22.  option   => "ListInput",
  23.  
  24.  button   => "SubmitInput",
  25.  submit   => "SubmitInput",
  26.  image    => "ImageInput",
  27.  file     => "FileInput",
  28.  
  29.  keygen   => "KeygenInput",
  30. );
  31.  
  32. =head1 NAME
  33.  
  34. HTML::Form - Class that represents an HTML form element
  35.  
  36. =head1 SYNOPSIS
  37.  
  38.  use HTML::Form;
  39.  $form = HTML::Form->parse($html, $base_uri);
  40.  $form->value(query => "Perl");
  41.  
  42.  use LWP::UserAgent;
  43.  $ua = LWP::UserAgent->new;
  44.  $response = $ua->request($form->click);
  45.  
  46. =head1 DESCRIPTION
  47.  
  48. Objects of the C<HTML::Form> class represents a single HTML
  49. C<E<lt>formE<gt> ... E<lt>/formE<gt>> instance.  A form consists of a
  50. sequence of inputs that usually have names, and which can take on
  51. various values.  The state of a form can be tweaked and it can then be
  52. asked to provide C<HTTP::Request> objects that can be passed to the
  53. request() method of C<LWP::UserAgent>.
  54.  
  55. The following methods are available:
  56.  
  57. =over 4
  58.  
  59. =item @forms = HTML::Form->parse( $response )
  60.  
  61. =item @forms = HTML::Form->parse( $html_document, $base )
  62.  
  63. =item @forms = HTML::Form->parse( $html_document, %opt )
  64.  
  65. The parse() class method will parse an HTML document and build up
  66. C<HTML::Form> objects for each <form> element found.  If called in scalar
  67. context only returns the first <form>.  Returns an empty list if there
  68. are no forms to be found.
  69.  
  70. The $base is the URI used to retrieve the $html_document.  It is
  71. needed to resolve relative action URIs.  If the document was retrieved
  72. with LWP then this this parameter is obtained from the
  73. $response->base() method, as shown by the following example:
  74.  
  75.     my $ua = LWP::UserAgent->new;
  76.     my $response = $ua->get("http://www.example.com/form.html");
  77.     my @forms = HTML::Form->parse($response->decoded_content,
  78.                   $response->base);
  79.  
  80. The parse() method can parse from an C<HTTP::Response> object
  81. directly, so the example above can be more conveniently written as:
  82.  
  83.     my $ua = LWP::UserAgent->new;
  84.     my $response = $ua->get("http://www.example.com/form.html");
  85.     my @forms = HTML::Form->parse($response);
  86.  
  87. Note that any object that implements a decoded_content() and base() method
  88. with similar behaviour as C<HTTP::Response> will do.
  89.  
  90. Finally options might be passed in to control how the parse method
  91. behaves.  The following options are currently recognized:
  92.  
  93. =over
  94.  
  95. =item C<< base => $uri >>
  96.  
  97. Another way to provide the base URI.
  98.  
  99. =item C<< verbose => $bool >>
  100.  
  101. Warn (print messages to STDERR) about any bad HTML form constructs found.
  102. You can trap these with $SIG{__WARN__}.
  103.  
  104. =item C<< strict => $bool >>
  105.  
  106. Initialize any form objects with the given strict attribute.
  107.  
  108. =back
  109.  
  110. =cut
  111.  
  112. sub parse
  113. {
  114.     my $class = shift;
  115.     my $html = shift;
  116.     unshift(@_, "base") if @_ == 1;
  117.     my %opt = @_;
  118.  
  119.     require HTML::TokeParser;
  120.     my $p = HTML::TokeParser->new(ref($html) ? $html->decoded_content(ref => 1) : \$html);
  121.     die "Failed to create HTML::TokeParser object" unless $p;
  122.  
  123.     my $base_uri = delete $opt{base};
  124.     my $strict = delete $opt{strict};
  125.     my $verbose = delete $opt{verbose};
  126.  
  127.     if ($^W) {
  128.     Carp::carp("Unrecognized option $_ in HTML::Form->parse") for sort keys %opt;
  129.     }
  130.  
  131.     unless (defined $base_uri) {
  132.     if (ref($html)) {
  133.         $base_uri = $html->base;
  134.     }
  135.     else {
  136.         Carp::croak("HTML::Form::parse: No \$base_uri provided");
  137.     }
  138.     }
  139.  
  140.     my @forms;
  141.     my $f;  # current form
  142.  
  143.     my %openselect; # index to the open instance of a select
  144.  
  145.     while (my $t = $p->get_tag) {
  146.     my($tag,$attr) = @$t;
  147.     if ($tag eq "form") {
  148.         my $action = delete $attr->{'action'};
  149.         $action = "" unless defined $action;
  150.         $action = URI->new_abs($action, $base_uri);
  151.         $f = $class->new($attr->{'method'},
  152.                  $action,
  153.                  $attr->{'enctype'});
  154.         $f->{attr} = $attr;
  155.         $f->strict(1) if $strict;
  156.             %openselect = ();
  157.         push(@forms, $f);
  158.         my(%labels, $current_label);
  159.         while (my $t = $p->get_tag) {
  160.         my($tag, $attr) = @$t;
  161.         last if $tag eq "/form";
  162.  
  163.         # if we are inside a label tag, then keep
  164.         # appending any text to the current label
  165.         if(defined $current_label) {
  166.             $current_label = join " ",
  167.                 grep { defined and length }
  168.                 $current_label,
  169.                 $p->get_phrase;
  170.         }
  171.  
  172.         if ($tag eq "input") {
  173.             $attr->{value_name} =
  174.                 exists $attr->{id} && exists $labels{$attr->{id}} ? $labels{$attr->{id}} :
  175.             defined $current_label                            ?  $current_label      :
  176.                 $p->get_phrase;
  177.         }
  178.  
  179.         if ($tag eq "label") {
  180.             $current_label = $p->get_phrase;
  181.             $labels{ $attr->{for} } = $current_label
  182.                 if exists $attr->{for};
  183.         }
  184.         elsif ($tag eq "/label") {
  185.             $current_label = undef;
  186.         }
  187.         elsif ($tag eq "input") {
  188.             my $type = delete $attr->{type} || "text";
  189.             $f->push_input($type, $attr, $verbose);
  190.         }
  191.                 elsif ($tag eq "button") {
  192.                     my $type = delete $attr->{type} || "submit";
  193.                     $f->push_input($type, $attr, $verbose);
  194.                 }
  195.         elsif ($tag eq "textarea") {
  196.             $attr->{textarea_value} = $attr->{value}
  197.                 if exists $attr->{value};
  198.             my $text = $p->get_text("/textarea");
  199.             $attr->{value} = $text;
  200.             $f->push_input("textarea", $attr, $verbose);
  201.         }
  202.         elsif ($tag eq "select") {
  203.             # rename attributes reserved to come for the option tag
  204.             for ("value", "value_name") {
  205.             $attr->{"select_$_"} = delete $attr->{$_}
  206.                 if exists $attr->{$_};
  207.             }
  208.             # count this new select option separately
  209.             $openselect{$attr->{name}}++;
  210.  
  211.             while ($t = $p->get_tag) {
  212.             my $tag = shift @$t;
  213.             last if $tag eq "/select";
  214.             next if $tag =~ m,/?optgroup,;
  215.             next if $tag eq "/option";
  216.             if ($tag eq "option") {
  217.                 my %a = %{$t->[0]};
  218.                 # rename keys so they don't clash with %attr
  219.                 for (keys %a) {
  220.                 next if $_ eq "value";
  221.                 $a{"option_$_"} = delete $a{$_};
  222.                 }
  223.                 while (my($k,$v) = each %$attr) {
  224.                 $a{$k} = $v;
  225.                 }
  226.                 $a{value_name} = $p->get_trimmed_text;
  227.                 $a{value} = delete $a{value_name}
  228.                 unless defined $a{value};
  229.                 $a{idx} = $openselect{$attr->{name}};
  230.                 $f->push_input("option", \%a, $verbose);
  231.             }
  232.             else {
  233.                 warn("Bad <select> tag '$tag' in $base_uri\n") if $verbose;
  234.                 if ($tag eq "/form" ||
  235.                 $tag eq "input" ||
  236.                 $tag eq "textarea" ||
  237.                 $tag eq "select" ||
  238.                 $tag eq "keygen")
  239.                 {
  240.                 # MSIE implictly terminate the <select> here, so we
  241.                 # try to do the same.  Actually the MSIE behaviour
  242.                 # appears really strange:  <input> and <textarea>
  243.                 # do implictly close, but not <select>, <keygen> or
  244.                 # </form>.
  245.                 my $type = ($tag =~ s,^/,,) ? "E" : "S";
  246.                 $p->unget_token([$type, $tag, @$t]);
  247.                 last;
  248.                 }
  249.             }
  250.             }
  251.         }
  252.         elsif ($tag eq "keygen") {
  253.             $f->push_input("keygen", $attr, $verbose);
  254.         }
  255.         }
  256.     }
  257.     elsif ($form_tags{$tag}) {
  258.         warn("<$tag> outside <form> in $base_uri\n") if $verbose;
  259.     }
  260.     }
  261.     for (@forms) {
  262.     $_->fixup;
  263.     }
  264.  
  265.     wantarray ? @forms : $forms[0];
  266. }
  267.  
  268. sub new {
  269.     my $class = shift;
  270.     my $self = bless {}, $class;
  271.     $self->{method} = uc(shift  || "GET");
  272.     $self->{action} = shift  || Carp::croak("No action defined");
  273.     $self->{enctype} = lc(shift || "application/x-www-form-urlencoded");
  274.     $self->{inputs} = [@_];
  275.     $self;
  276. }
  277.  
  278.  
  279. sub push_input
  280. {
  281.     my($self, $type, $attr, $verbose) = @_;
  282.     $type = lc $type;
  283.     my $class = $type2class{$type};
  284.     unless ($class) {
  285.     Carp::carp("Unknown input type '$type'") if $verbose;
  286.     $class = "TextInput";
  287.     }
  288.     $class = "HTML::Form::$class";
  289.     my @extra;
  290.     push(@extra, readonly => 1) if $type eq "hidden";
  291.     push(@extra, strict => 1) if $self->{strict};
  292.  
  293.     delete $attr->{type}; # don't confuse the type argument
  294.     my $input = $class->new(type => $type, %$attr, @extra);
  295.     $input->add_to_form($self);
  296. }
  297.  
  298.  
  299. =item $method = $form->method
  300.  
  301. =item $form->method( $new_method )
  302.  
  303. This method is gets/sets the I<method> name used for the
  304. C<HTTP::Request> generated.  It is a string like "GET" or "POST".
  305.  
  306. =item $action = $form->action
  307.  
  308. =item $form->action( $new_action )
  309.  
  310. This method gets/sets the URI which we want to apply the request
  311. I<method> to.
  312.  
  313. =item $enctype = $form->enctype
  314.  
  315. =item $form->enctype( $new_enctype )
  316.  
  317. This method gets/sets the encoding type for the form data.  It is a
  318. string like "application/x-www-form-urlencoded" or "multipart/form-data".
  319.  
  320. =cut
  321.  
  322. BEGIN {
  323.     # Set up some accesor
  324.     for (qw(method action enctype)) {
  325.     my $m = $_;
  326.     no strict 'refs';
  327.     *{$m} = sub {
  328.         my $self = shift;
  329.         my $old = $self->{$m};
  330.         $self->{$m} = shift if @_;
  331.         $old;
  332.     };
  333.     }
  334.     *uri = \&action;  # alias
  335. }
  336.  
  337. =item $value = $form->attr( $name )
  338.  
  339. =item $form->attr( $name, $new_value )
  340.  
  341. This method give access to the original HTML attributes of the <form> tag.
  342. The $name should always be passed in lower case.
  343.  
  344. Example:
  345.  
  346.    @f = HTML::Form->parse( $html, $foo );
  347.    @f = grep $_->attr("id") eq "foo", @f;
  348.    die "No form named 'foo' found" unless @f;
  349.    $foo = shift @f;
  350.  
  351. =cut
  352.  
  353. sub attr {
  354.     my $self = shift;
  355.     my $name = shift;
  356.     return undef unless defined $name;
  357.  
  358.     my $old = $self->{attr}{$name};
  359.     $self->{attr}{$name} = shift if @_;
  360.     return $old;
  361. }
  362.  
  363. =item $bool = $form->strict
  364.  
  365. =item $form->strict( $bool )
  366.  
  367. Gets/sets the strict attribute of a form.  If the strict is turned on
  368. the methods that change values of the form will croak if you try to
  369. set illegal values or modify readonly fields.  The default is not to be strict.
  370.  
  371. =cut
  372.  
  373. sub strict {
  374.     my $self = shift;
  375.     my $old = $self->{strict};
  376.     if (@_) {
  377.     $self->{strict} = shift;
  378.     for my $input (@{$self->{inputs}}) {
  379.         $input->strict($self->{strict});
  380.     }
  381.     }
  382.     return $old;
  383. }
  384.  
  385.  
  386. =item @inputs = $form->inputs
  387.  
  388. This method returns the list of inputs in the form.  If called in
  389. scalar context it returns the number of inputs contained in the form.
  390. See L</INPUTS> for what methods are available for the input objects
  391. returned.
  392.  
  393. =cut
  394.  
  395. sub inputs
  396. {
  397.     my $self = shift;
  398.     @{$self->{'inputs'}};
  399. }
  400.  
  401.  
  402. =item $input = $form->find_input( $name )
  403.  
  404. =item $input = $form->find_input( $name, $type )
  405.  
  406. =item $input = $form->find_input( $name, $type, $index )
  407.  
  408. This method is used to locate specific inputs within the form.  All
  409. inputs that match the arguments given are returned.  In scalar context
  410. only the first is returned, or C<undef> if none match.
  411.  
  412. If $name is specified, then the input must have the indicated name.
  413.  
  414. If $type is specified, then the input must have the specified type.
  415. The following type names are used: "text", "password", "hidden",
  416. "textarea", "file", "image", "submit", "radio", "checkbox" and "option".
  417.  
  418. The $index is the sequence number of the input matched where 1 is the
  419. first.  If combined with $name and/or $type then it select the I<n>th
  420. input with the given name and/or type.
  421.  
  422. =cut
  423.  
  424. sub find_input
  425. {
  426.     my($self, $name, $type, $no) = @_;
  427.     if (wantarray) {
  428.     my @res;
  429.     my $c;
  430.     for (@{$self->{'inputs'}}) {
  431.         if (defined $name) {
  432.         next unless exists $_->{name};
  433.         next if $name ne $_->{name};
  434.         }
  435.         next if $type && $type ne $_->{type};
  436.         $c++;
  437.         next if $no && $no != $c;
  438.         push(@res, $_);
  439.     }
  440.     return @res;
  441.     
  442.     }
  443.     else {
  444.     $no ||= 1;
  445.     for (@{$self->{'inputs'}}) {
  446.         if (defined $name) {
  447.         next unless exists $_->{name};
  448.         next if $name ne $_->{name};
  449.         }
  450.         next if $type && $type ne $_->{type};
  451.         next if --$no;
  452.         return $_;
  453.     }
  454.     return undef;
  455.     }
  456. }
  457.  
  458. sub fixup
  459. {
  460.     my $self = shift;
  461.     for (@{$self->{'inputs'}}) {
  462.     $_->fixup;
  463.     }
  464. }
  465.  
  466.  
  467. =item $value = $form->value( $name )
  468.  
  469. =item $form->value( $name, $new_value )
  470.  
  471. The value() method can be used to get/set the value of some input.  If
  472. strict is enabled and no input has the indicated name, then this method will croak.
  473.  
  474. If multiple inputs have the same name, only the first one will be
  475. affected.
  476.  
  477. The call:
  478.  
  479.     $form->value('foo')
  480.  
  481. is basically a short-hand for:
  482.  
  483.     $form->find_input('foo')->value;
  484.  
  485. =cut
  486.  
  487. sub value
  488. {
  489.     my $self = shift;
  490.     my $key  = shift;
  491.     my $input = $self->find_input($key);
  492.     unless ($input) {
  493.     Carp::croak("No such field '$key'") if $self->{strict};
  494.     return undef unless @_;
  495.     $input = $self->push_input("text", { name => $key, value => "" });
  496.     }
  497.     local $Carp::CarpLevel = 1;
  498.     $input->value(@_);
  499. }
  500.  
  501. =item @names = $form->param
  502.  
  503. =item @values = $form->param( $name )
  504.  
  505. =item $form->param( $name, $value, ... )
  506.  
  507. =item $form->param( $name, \@values )
  508.  
  509. Alternative interface to examining and setting the values of the form.
  510.  
  511. If called without arguments then it returns the names of all the
  512. inputs in the form.  The names will not repeat even if multiple inputs
  513. have the same name.  In scalar context the number of different names
  514. is returned.
  515.  
  516. If called with a single argument then it returns the value or values
  517. of inputs with the given name.  If called in scalar context only the
  518. first value is returned.  If no input exists with the given name, then
  519. C<undef> is returned.
  520.  
  521. If called with 2 or more arguments then it will set values of the
  522. named inputs.  This form will croak if no inputs have the given name
  523. or if any of the values provided does not fit.  Values can also be
  524. provided as a reference to an array.  This form will allow unsetting
  525. all values with the given name as well.
  526.  
  527. This interface resembles that of the param() function of the CGI
  528. module.
  529.  
  530. =cut
  531.  
  532. sub param {
  533.     my $self = shift;
  534.     if (@_) {
  535.         my $name = shift;
  536.         my @inputs;
  537.         for ($self->inputs) {
  538.             my $n = $_->name;
  539.             next if !defined($n) || $n ne $name;
  540.             push(@inputs, $_);
  541.         }
  542.  
  543.         if (@_) {
  544.             # set
  545.             die "No '$name' parameter exists" unless @inputs;
  546.         my @v = @_;
  547.         @v = @{$v[0]} if @v == 1 && ref($v[0]);
  548.             while (@v) {
  549.                 my $v = shift @v;
  550.                 my $err;
  551.                 for my $i (0 .. @inputs-1) {
  552.                     eval {
  553.                         $inputs[$i]->value($v);
  554.                     };
  555.                     unless ($@) {
  556.                         undef($err);
  557.                         splice(@inputs, $i, 1);
  558.                         last;
  559.                     }
  560.                     $err ||= $@;
  561.                 }
  562.                 die $err if $err;
  563.             }
  564.  
  565.         # the rest of the input should be cleared
  566.         for (@inputs) {
  567.         $_->value(undef);
  568.         }
  569.         }
  570.         else {
  571.             # get
  572.             my @v;
  573.             for (@inputs) {
  574.         if (defined(my $v = $_->value)) {
  575.             push(@v, $v);
  576.         }
  577.             }
  578.             return wantarray ? @v : $v[0];
  579.         }
  580.     }
  581.     else {
  582.         # list parameter names
  583.         my @n;
  584.         my %seen;
  585.         for ($self->inputs) {
  586.             my $n = $_->name;
  587.             next if !defined($n) || $seen{$n}++;
  588.             push(@n, $n);
  589.         }
  590.         return @n;
  591.     }
  592. }
  593.  
  594.  
  595. =item $form->try_others( \&callback )
  596.  
  597. This method will iterate over all permutations of unvisited enumerated
  598. values (<select>, <radio>, <checkbox>) and invoke the callback for
  599. each.  The callback is passed the $form as argument.  The return value
  600. from the callback is ignored and the try_others() method itself does
  601. not return anything.
  602.  
  603. =cut
  604.  
  605. sub try_others
  606. {
  607.     my($self, $cb) = @_;
  608.     my @try;
  609.     for (@{$self->{'inputs'}}) {
  610.     my @not_tried_yet = $_->other_possible_values;
  611.     next unless @not_tried_yet;
  612.     push(@try, [\@not_tried_yet, $_]);
  613.     }
  614.     return unless @try;
  615.     $self->_try($cb, \@try, 0);
  616. }
  617.  
  618. sub _try
  619. {
  620.     my($self, $cb, $try, $i) = @_;
  621.     for (@{$try->[$i][0]}) {
  622.     $try->[$i][1]->value($_);
  623.     &$cb($self);
  624.     $self->_try($cb, $try, $i+1) if $i+1 < @$try;
  625.     }
  626. }
  627.  
  628.  
  629. =item $request = $form->make_request
  630.  
  631. Will return an C<HTTP::Request> object that reflects the current setting
  632. of the form.  You might want to use the click() method instead.
  633.  
  634. =cut
  635.  
  636. sub make_request
  637. {
  638.     my $self = shift;
  639.     my $method  = uc $self->{'method'};
  640.     my $uri     = $self->{'action'};
  641.     my $enctype = $self->{'enctype'};
  642.     my @form    = $self->form;
  643.  
  644.     if ($method eq "GET") {
  645.     require HTTP::Request;
  646.     $uri = URI->new($uri, "http");
  647.     $uri->query_form(@form);
  648.     return HTTP::Request->new(GET => $uri);
  649.     }
  650.     elsif ($method eq "POST") {
  651.     require HTTP::Request::Common;
  652.     return HTTP::Request::Common::POST($uri, \@form,
  653.                        Content_Type => $enctype);
  654.     }
  655.     else {
  656.     Carp::croak("Unknown method '$method'");
  657.     }
  658. }
  659.  
  660.  
  661. =item $request = $form->click
  662.  
  663. =item $request = $form->click( $name )
  664.  
  665. =item $request = $form->click( $x, $y )
  666.  
  667. =item $request = $form->click( $name, $x, $y )
  668.  
  669. Will "click" on the first clickable input (which will be of type
  670. C<submit> or C<image>).  The result of clicking is an C<HTTP::Request>
  671. object that can then be passed to C<LWP::UserAgent> if you want to
  672. obtain the server response.
  673.  
  674. If a $name is specified, we will click on the first clickable input
  675. with the given name, and the method will croak if no clickable input
  676. with the given name is found.  If $name is I<not> specified, then it
  677. is ok if the form contains no clickable inputs.  In this case the
  678. click() method returns the same request as the make_request() method
  679. would do.
  680.  
  681. If there are multiple clickable inputs with the same name, then there
  682. is no way to get the click() method of the C<HTML::Form> to click on
  683. any but the first.  If you need this you would have to locate the
  684. input with find_input() and invoke the click() method on the given
  685. input yourself.
  686.  
  687. A click coordinate pair can also be provided, but this only makes a
  688. difference if you clicked on an image.  The default coordinate is
  689. (1,1).  The upper-left corner of the image is (0,0), but some badly
  690. coded CGI scripts are known to not recognize this.  Therefore (1,1) was
  691. selected as a safer default.
  692.  
  693. =cut
  694.  
  695. sub click
  696. {
  697.     my $self = shift;
  698.     my $name;
  699.     $name = shift if (@_ % 2) == 1;  # odd number of arguments
  700.  
  701.     # try to find first submit button to activate
  702.     for (@{$self->{'inputs'}}) {
  703.         next unless $_->can("click");
  704.         next if $name && $_->name ne $name;
  705.     next if $_->disabled;
  706.     return $_->click($self, @_);
  707.     }
  708.     Carp::croak("No clickable input with name $name") if $name;
  709.     $self->make_request;
  710. }
  711.  
  712.  
  713. =item @kw = $form->form
  714.  
  715. Returns the current setting as a sequence of key/value pairs.  Note
  716. that keys might be repeated, which means that some values might be
  717. lost if the return values are assigned to a hash.
  718.  
  719. In scalar context this method returns the number of key/value pairs
  720. generated.
  721.  
  722. =cut
  723.  
  724. sub form
  725. {
  726.     my $self = shift;
  727.     map { $_->form_name_value($self) } @{$self->{'inputs'}};
  728. }
  729.  
  730.  
  731. =item $form->dump
  732.  
  733. Returns a textual representation of current state of the form.  Mainly
  734. useful for debugging.  If called in void context, then the dump is
  735. printed on STDERR.
  736.  
  737. =cut
  738.  
  739. sub dump
  740. {
  741.     my $self = shift;
  742.     my $method  = $self->{'method'};
  743.     my $uri     = $self->{'action'};
  744.     my $enctype = $self->{'enctype'};
  745.     my $dump = "$method $uri";
  746.     $dump .= " ($enctype)"
  747.     if $enctype ne "application/x-www-form-urlencoded";
  748.     $dump .= " [$self->{attr}{name}]"
  749.         if exists $self->{attr}{name};
  750.     $dump .= "\n";
  751.     for ($self->inputs) {
  752.     $dump .= "  " . $_->dump . "\n";
  753.     }
  754.     print STDERR $dump unless defined wantarray;
  755.     $dump;
  756. }
  757.  
  758.  
  759. #---------------------------------------------------
  760. package HTML::Form::Input;
  761.  
  762. =back
  763.  
  764. =head1 INPUTS
  765.  
  766. An C<HTML::Form> objects contains a sequence of I<inputs>.  References to
  767. the inputs can be obtained with the $form->inputs or $form->find_input
  768. methods.
  769.  
  770. Note that there is I<not> a one-to-one correspondence between input
  771. I<objects> and E<lt>inputE<gt> I<elements> in the HTML document.  An
  772. input object basically represents a name/value pair, so when multiple
  773. HTML elements contribute to the same name/value pair in the submitted
  774. form they are combined.
  775.  
  776. The input elements that are mapped one-to-one are "text", "textarea",
  777. "password", "hidden", "file", "image", "submit" and "checkbox".  For
  778. the "radio" and "option" inputs the story is not as simple: All
  779. E<lt>input type="radio"E<gt> elements with the same name will
  780. contribute to the same input radio object.  The number of radio input
  781. objects will be the same as the number of distinct names used for the
  782. E<lt>input type="radio"E<gt> elements.  For a E<lt>selectE<gt> element
  783. without the C<multiple> attribute there will be one input object of
  784. type of "option".  For a E<lt>select multipleE<gt> element there will
  785. be one input object for each contained E<lt>optionE<gt> element.  Each
  786. one of these option objects will have the same name.
  787.  
  788. The following methods are available for the I<input> objects:
  789.  
  790. =over 4
  791.  
  792. =cut
  793.  
  794. sub new
  795. {
  796.     my $class = shift;
  797.     my $self = bless {@_}, $class;
  798.     $self;
  799. }
  800.  
  801. sub add_to_form
  802. {
  803.     my($self, $form) = @_;
  804.     push(@{$form->{'inputs'}}, $self);
  805.     $self;
  806. }
  807.  
  808. sub strict {
  809.     my $self = shift;
  810.     my $old = $self->{strict};
  811.     if (@_) {
  812.     $self->{strict} = shift;
  813.     }
  814.     $old;
  815. }
  816.  
  817. sub fixup {}
  818.  
  819.  
  820. =item $input->type
  821.  
  822. Returns the type of this input.  The type is one of the following
  823. strings: "text", "password", "hidden", "textarea", "file", "image", "submit",
  824. "radio", "checkbox" or "option".
  825.  
  826. =cut
  827.  
  828. sub type
  829. {
  830.     shift->{type};
  831. }
  832.  
  833. =item $name = $input->name
  834.  
  835. =item $input->name( $new_name )
  836.  
  837. This method can be used to get/set the current name of the input.
  838.  
  839. =item $value = $input->value
  840.  
  841. =item $input->value( $new_value )
  842.  
  843. This method can be used to get/set the current value of an
  844. input.
  845.  
  846. If strict is enabled and the input only can take an enumerated list of values,
  847. then it is an error to try to set it to something else and the method will
  848. croak if you try.
  849.  
  850. You will also be able to set the value of read-only inputs, but a
  851. warning will be generated if running under C<perl -w>.
  852.  
  853. =cut
  854.  
  855. sub name
  856. {
  857.     my $self = shift;
  858.     my $old = $self->{name};
  859.     $self->{name} = shift if @_;
  860.     $old;
  861. }
  862.  
  863. sub value
  864. {
  865.     my $self = shift;
  866.     my $old = $self->{value};
  867.     $self->{value} = shift if @_;
  868.     $old;
  869. }
  870.  
  871. =item $input->possible_values
  872.  
  873. Returns a list of all values that an input can take.  For inputs that
  874. do not have discrete values, this returns an empty list.
  875.  
  876. =cut
  877.  
  878. sub possible_values
  879. {
  880.     return;
  881. }
  882.  
  883. =item $input->other_possible_values
  884.  
  885. Returns a list of all values not tried yet.
  886.  
  887. =cut
  888.  
  889. sub other_possible_values
  890. {
  891.     return;
  892. }
  893.  
  894. =item $input->value_names
  895.  
  896. For some inputs the values can have names that are different from the
  897. values themselves.  The number of names returned by this method will
  898. match the number of values reported by $input->possible_values.
  899.  
  900. When setting values using the value() method it is also possible to
  901. use the value names in place of the value itself.
  902.  
  903. =cut
  904.  
  905. sub value_names {
  906.     return
  907. }
  908.  
  909. =item $bool = $input->readonly
  910.  
  911. =item $input->readonly( $bool )
  912.  
  913. This method is used to get/set the value of the readonly attribute.
  914. You are allowed to modify the value of readonly inputs, but setting
  915. the value will generate some noise when warnings are enabled.  Hidden
  916. fields always start out readonly.
  917.  
  918. =cut
  919.  
  920. sub readonly {
  921.     my $self = shift;
  922.     my $old = $self->{readonly};
  923.     $self->{readonly} = shift if @_;
  924.     $old;
  925. }
  926.  
  927. =item $bool = $input->disabled
  928.  
  929. =item $input->disabled( $bool )
  930.  
  931. This method is used to get/set the value of the disabled attribute.
  932. Disabled inputs do not contribute any key/value pairs for the form
  933. value.
  934.  
  935. =cut
  936.  
  937. sub disabled {
  938.     my $self = shift;
  939.     my $old = $self->{disabled};
  940.     $self->{disabled} = shift if @_;
  941.     $old;
  942. }
  943.  
  944. =item $input->form_name_value
  945.  
  946. Returns a (possible empty) list of key/value pairs that should be
  947. incorporated in the form value from this input.
  948.  
  949. =cut
  950.  
  951. sub form_name_value
  952. {
  953.     my $self = shift;
  954.     my $name = $self->{'name'};
  955.     return unless defined $name;
  956.     return if $self->disabled;
  957.     my $value = $self->value;
  958.     return unless defined $value;
  959.     return ($name => $value);
  960. }
  961.  
  962. sub dump
  963. {
  964.     my $self = shift;
  965.     my $name = $self->name;
  966.     $name = "<NONAME>" unless defined $name;
  967.     my $value = $self->value;
  968.     $value = "<UNDEF>" unless defined $value;
  969.     my $dump = "$name=$value";
  970.  
  971.     my $type = $self->type;
  972.  
  973.     $type .= " disabled" if $self->disabled;
  974.     $type .= " readonly" if $self->readonly;
  975.     return sprintf "%-30s %s", $dump, "($type)" unless $self->{menu};
  976.  
  977.     my @menu;
  978.     my $i = 0;
  979.     for (@{$self->{menu}}) {
  980.     my $opt = $_->{value};
  981.     $opt = "<UNDEF>" unless defined $opt;
  982.     $opt .= "/$_->{name}"
  983.         if defined $_->{name} && length $_->{name} && $_->{name} ne $opt;
  984.     substr($opt,0,0) = "-" if $_->{disabled};
  985.     if (exists $self->{current} && $self->{current} == $i) {
  986.         substr($opt,0,0) = "!" unless $_->{seen};
  987.         substr($opt,0,0) = "*";
  988.     }
  989.     else {
  990.         substr($opt,0,0) = ":" if $_->{seen};
  991.     }
  992.     push(@menu, $opt);
  993.     $i++;
  994.     }
  995.  
  996.     return sprintf "%-30s %-10s %s", $dump, "($type)", "[" . join("|", @menu) . "]";
  997. }
  998.  
  999.  
  1000. #---------------------------------------------------
  1001. package HTML::Form::TextInput;
  1002. @HTML::Form::TextInput::ISA=qw(HTML::Form::Input);
  1003.  
  1004. #input/text
  1005. #input/password
  1006. #input/hidden
  1007. #textarea
  1008.  
  1009. sub value
  1010. {
  1011.     my $self = shift;
  1012.     my $old = $self->{value};
  1013.     $old = "" unless defined $old;
  1014.     if (@_) {
  1015.         Carp::croak("Input '$self->{name}' is readonly")
  1016.         if $self->{strict} && $self->{readonly};
  1017.         my $new = shift;
  1018.         my $n = exists $self->{maxlength} ? $self->{maxlength} : undef;
  1019.         Carp::croak("Input '$self->{name}' has maxlength '$n'")
  1020.         if $self->{strict} && defined($n) && defined($new) && length($new) > $n;
  1021.     $self->{value} = $new;
  1022.     }
  1023.     $old;
  1024. }
  1025.  
  1026. #---------------------------------------------------
  1027. package HTML::Form::IgnoreInput;
  1028. @HTML::Form::IgnoreInput::ISA=qw(HTML::Form::Input);
  1029.  
  1030. #input/button
  1031. #input/reset
  1032.  
  1033. sub value { return }
  1034.  
  1035.  
  1036. #---------------------------------------------------
  1037. package HTML::Form::ListInput;
  1038. @HTML::Form::ListInput::ISA=qw(HTML::Form::Input);
  1039.  
  1040. #select/option   (val1, val2, ....)
  1041. #input/radio     (undef, val1, val2,...)
  1042. #input/checkbox  (undef, value)
  1043. #select-multiple/option (undef, value)
  1044.  
  1045. sub new
  1046. {
  1047.     my $class = shift;
  1048.     my $self = $class->SUPER::new(@_);
  1049.  
  1050.     my $value = delete $self->{value};
  1051.     my $value_name = delete $self->{value_name};
  1052.     my $type = $self->{type};
  1053.  
  1054.     if ($type eq "checkbox") {
  1055.     $value = "on" unless defined $value;
  1056.     $self->{menu} = [
  1057.         { value => undef, name => "off", },
  1058.             { value => $value, name => $value_name, },
  1059.         ];
  1060.     $self->{current} = (delete $self->{checked}) ? 1 : 0;
  1061.     ;
  1062.     }
  1063.     else {
  1064.     $self->{option_disabled}++
  1065.         if $type eq "radio" && delete $self->{disabled};
  1066.     $self->{menu} = [
  1067.             {value => $value, name => $value_name},
  1068.         ];
  1069.     my $checked = $self->{checked} || $self->{option_selected};
  1070.     delete $self->{checked};
  1071.     delete $self->{option_selected};
  1072.     if (exists $self->{multiple}) {
  1073.         unshift(@{$self->{menu}}, { value => undef, name => "off"});
  1074.         $self->{current} = $checked ? 1 : 0;
  1075.     }
  1076.     else {
  1077.         $self->{current} = 0 if $checked;
  1078.     }
  1079.     }
  1080.     $self;
  1081. }
  1082.  
  1083. sub add_to_form
  1084. {
  1085.     my($self, $form) = @_;
  1086.     my $type = $self->type;
  1087.  
  1088.     return $self->SUPER::add_to_form($form)
  1089.     if $type eq "checkbox";
  1090.  
  1091.     if ($type eq "option" && exists $self->{multiple}) {
  1092.     $self->{disabled} ||= delete $self->{option_disabled};
  1093.     return $self->SUPER::add_to_form($form);
  1094.     }
  1095.  
  1096.     die "Assert" if @{$self->{menu}} != 1;
  1097.     my $m = $self->{menu}[0];
  1098.     $m->{disabled}++ if delete $self->{option_disabled};
  1099.  
  1100.     my $prev = $form->find_input($self->{name}, $self->{type}, $self->{idx});
  1101.     return $self->SUPER::add_to_form($form) unless $prev;
  1102.  
  1103.     # merge menues
  1104.     $prev->{current} = @{$prev->{menu}} if exists $self->{current};
  1105.     push(@{$prev->{menu}}, $m);
  1106. }
  1107.  
  1108. sub fixup
  1109. {
  1110.     my $self = shift;
  1111.     if ($self->{type} eq "option" && !(exists $self->{current})) {
  1112.     $self->{current} = 0;
  1113.     }
  1114.     $self->{menu}[$self->{current}]{seen}++ if exists $self->{current};
  1115. }
  1116.  
  1117. sub disabled
  1118. {
  1119.     my $self = shift;
  1120.     my $type = $self->type;
  1121.  
  1122.     my $old = $self->{disabled} || _menu_all_disabled(@{$self->{menu}});
  1123.     if (@_) {
  1124.     my $v = shift;
  1125.     $self->{disabled} = $v;
  1126.         for (@{$self->{menu}}) {
  1127.             $_->{disabled} = $v;
  1128.         }
  1129.     }
  1130.     return $old;
  1131. }
  1132.  
  1133. sub _menu_all_disabled {
  1134.     for (@_) {
  1135.     return 0 unless $_->{disabled};
  1136.     }
  1137.     return 1;
  1138. }
  1139.  
  1140. sub value
  1141. {
  1142.     my $self = shift;
  1143.     my $old;
  1144.     $old = $self->{menu}[$self->{current}]{value} if exists $self->{current};
  1145.     $old = $self->{value} if exists $self->{value};
  1146.     if (@_) {
  1147.     my $i = 0;
  1148.     my $val = shift;
  1149.     my $cur;
  1150.     my $disabled;
  1151.     for (@{$self->{menu}}) {
  1152.         if ((defined($val) && defined($_->{value}) && $val eq $_->{value}) ||
  1153.         (!defined($val) && !defined($_->{value}))
  1154.            )
  1155.         {
  1156.         $cur = $i;
  1157.         $disabled = $_->{disabled};
  1158.         last unless $disabled;
  1159.         }
  1160.         $i++;
  1161.     }
  1162.     if (!(defined $cur) || $disabled) {
  1163.         if (defined $val) {
  1164.         # try to search among the alternative names as well
  1165.         my $i = 0;
  1166.         my $cur_ignorecase;
  1167.         my $lc_val = lc($val);
  1168.         for (@{$self->{menu}}) {
  1169.             if (defined $_->{name}) {
  1170.             if ($val eq $_->{name}) {
  1171.                 $disabled = $_->{disabled};
  1172.                 $cur = $i;
  1173.                 last unless $disabled;
  1174.             }
  1175.             if (!defined($cur_ignorecase) && $lc_val eq lc($_->{name})) {
  1176.                 $cur_ignorecase = $i;
  1177.             }
  1178.             }
  1179.             $i++;
  1180.         }
  1181.         unless (defined $cur) {
  1182.             $cur = $cur_ignorecase;
  1183.             if (defined $cur) {
  1184.             $disabled = $self->{menu}[$cur]{disabled};
  1185.             }
  1186.             elsif ($self->{strict}) {
  1187.             my $n = $self->name;
  1188.                 Carp::croak("Illegal value '$val' for field '$n'");
  1189.             }
  1190.         }
  1191.         }
  1192.         elsif ($self->{strict}) {
  1193.         my $n = $self->name;
  1194.             Carp::croak("The '$n' field can't be unchecked");
  1195.         }
  1196.     }
  1197.     if ($self->{strict} && $disabled) {
  1198.         my $n = $self->name;
  1199.         Carp::croak("The value '$val' has been disabled for field '$n'");
  1200.     }
  1201.     if (defined $cur) {
  1202.         $self->{current} = $cur;
  1203.         $self->{menu}[$cur]{seen}++;
  1204.         delete $self->{value};
  1205.     }
  1206.     else {
  1207.         $self->{value} = $val;
  1208.         delete $self->{current};
  1209.     }
  1210.     }
  1211.     $old;
  1212. }
  1213.  
  1214. =item $input->check
  1215.  
  1216. Some input types represent toggles that can be turned on/off.  This
  1217. includes "checkbox" and "option" inputs.  Calling this method turns
  1218. this input on without having to know the value name.  If the input is
  1219. already on, then nothing happens.
  1220.  
  1221. This has the same effect as:
  1222.  
  1223.     $input->value($input->possible_values[1]);
  1224.  
  1225. The input can be turned off with:
  1226.  
  1227.     $input->value(undef);
  1228.  
  1229. =cut
  1230.  
  1231. sub check
  1232. {
  1233.     my $self = shift;
  1234.     $self->{current} = 1;
  1235.     $self->{menu}[1]{seen}++;
  1236. }
  1237.  
  1238. sub possible_values
  1239. {
  1240.     my $self = shift;
  1241.     map $_->{value}, grep !$_->{disabled}, @{$self->{menu}};
  1242. }
  1243.  
  1244. sub other_possible_values
  1245. {
  1246.     my $self = shift;
  1247.     map $_->{value}, grep !$_->{seen} && !$_->{disabled}, @{$self->{menu}};
  1248. }
  1249.  
  1250. sub value_names {
  1251.     my $self = shift;
  1252.     my @names;
  1253.     for (@{$self->{menu}}) {
  1254.     my $n = $_->{name};
  1255.     $n = $_->{value} unless defined $n;
  1256.     push(@names, $n);
  1257.     }
  1258.     @names;
  1259. }
  1260.  
  1261.  
  1262. #---------------------------------------------------
  1263. package HTML::Form::SubmitInput;
  1264. @HTML::Form::SubmitInput::ISA=qw(HTML::Form::Input);
  1265.  
  1266. #input/image
  1267. #input/submit
  1268.  
  1269. =item $input->click($form, $x, $y)
  1270.  
  1271. Some input types (currently "submit" buttons and "images") can be
  1272. clicked to submit the form.  The click() method returns the
  1273. corresponding C<HTTP::Request> object.
  1274.  
  1275. =cut
  1276.  
  1277. sub click
  1278. {
  1279.     my($self,$form,$x,$y) = @_;
  1280.     for ($x, $y) { $_ = 1 unless defined; }
  1281.     local($self->{clicked}) = [$x,$y];
  1282.     return $form->make_request;
  1283. }
  1284.  
  1285. sub form_name_value
  1286. {
  1287.     my $self = shift;
  1288.     return unless $self->{clicked};
  1289.     return $self->SUPER::form_name_value(@_);
  1290. }
  1291.  
  1292.  
  1293. #---------------------------------------------------
  1294. package HTML::Form::ImageInput;
  1295. @HTML::Form::ImageInput::ISA=qw(HTML::Form::SubmitInput);
  1296.  
  1297. sub form_name_value
  1298. {
  1299.     my $self = shift;
  1300.     my $clicked = $self->{clicked};
  1301.     return unless $clicked;
  1302.     return if $self->{disabled};
  1303.     my $name = $self->{name};
  1304.     $name = (defined($name) && length($name)) ? "$name." : "";
  1305.     return ("${name}x" => $clicked->[0],
  1306.         "${name}y" => $clicked->[1]
  1307.        );
  1308. }
  1309.  
  1310. #---------------------------------------------------
  1311. package HTML::Form::FileInput;
  1312. @HTML::Form::FileInput::ISA=qw(HTML::Form::TextInput);
  1313.  
  1314. =back
  1315.  
  1316. If the input is of type C<file>, then it has these additional methods:
  1317.  
  1318. =over 4
  1319.  
  1320. =item $input->file
  1321.  
  1322. This is just an alias for the value() method.  It sets the filename to
  1323. read data from.
  1324.  
  1325. =cut
  1326.  
  1327. sub file {
  1328.     my $self = shift;
  1329.     $self->value(@_);
  1330. }
  1331.  
  1332. =item $filename = $input->filename
  1333.  
  1334. =item $input->filename( $new_filename )
  1335.  
  1336. This get/sets the filename reported to the server during file upload.
  1337. This attribute defaults to the value reported by the file() method.
  1338.  
  1339. =cut
  1340.  
  1341. sub filename {
  1342.     my $self = shift;
  1343.     my $old = $self->{filename};
  1344.     $self->{filename} = shift if @_;
  1345.     $old = $self->file unless defined $old;
  1346.     $old;
  1347. }
  1348.  
  1349. =item $content = $input->content
  1350.  
  1351. =item $input->content( $new_content )
  1352.  
  1353. This get/sets the file content provided to the server during file
  1354. upload.  This method can be used if you do not want the content to be
  1355. read from an actual file.
  1356.  
  1357. =cut
  1358.  
  1359. sub content {
  1360.     my $self = shift;
  1361.     my $old = $self->{content};
  1362.     $self->{content} = shift if @_;
  1363.     $old;
  1364. }
  1365.  
  1366. =item @headers = $input->headers
  1367.  
  1368. =item input->headers($key => $value, .... )
  1369.  
  1370. This get/set additional header fields describing the file uploaded.
  1371. This can for instance be used to set the C<Content-Type> reported for
  1372. the file.
  1373.  
  1374. =cut
  1375.  
  1376. sub headers {
  1377.     my $self = shift;
  1378.     my $old = $self->{headers} || [];
  1379.     $self->{headers} = [@_] if @_;
  1380.     @$old;
  1381. }
  1382.  
  1383. sub form_name_value {
  1384.     my($self, $form) = @_;
  1385.     return $self->SUPER::form_name_value($form)
  1386.     if $form->method ne "POST" ||
  1387.        $form->enctype ne "multipart/form-data";
  1388.  
  1389.     my $name = $self->name;
  1390.     return unless defined $name;
  1391.     return if $self->{disabled};
  1392.  
  1393.     my $file = $self->file;
  1394.     my $filename = $self->filename;
  1395.     my @headers = $self->headers;
  1396.     my $content = $self->content;
  1397.     if (defined $content) {
  1398.     $filename = $file unless defined $filename;
  1399.     $file = undef;
  1400.     unshift(@headers, "Content" => $content);
  1401.     }
  1402.     elsif (!defined($file) || length($file) == 0) {
  1403.     return;
  1404.     }
  1405.  
  1406.     # legacy (this used to be the way to do it)
  1407.     if (ref($file) eq "ARRAY") {
  1408.     my $f = shift @$file;
  1409.     my $fn = shift @$file;
  1410.     push(@headers, @$file);
  1411.     $file = $f;
  1412.     $filename = $fn unless defined $filename;
  1413.     }
  1414.  
  1415.     return ($name => [$file, $filename, @headers]);
  1416. }
  1417.  
  1418. package HTML::Form::KeygenInput;
  1419. @HTML::Form::KeygenInput::ISA=qw(HTML::Form::Input);
  1420.  
  1421. sub challenge {
  1422.     my $self = shift;
  1423.     return $self->{challenge};
  1424. }
  1425.  
  1426. sub keytype {
  1427.     my $self = shift;
  1428.     return lc($self->{keytype} || 'rsa');
  1429. }
  1430.  
  1431. 1;
  1432.  
  1433. __END__
  1434.  
  1435. =back
  1436.  
  1437. =head1 SEE ALSO
  1438.  
  1439. L<LWP>, L<LWP::UserAgent>, L<HTML::Parser>
  1440.  
  1441. =head1 COPYRIGHT
  1442.  
  1443. Copyright 1998-2008 Gisle Aas.
  1444.  
  1445. This library is free software; you can redistribute it and/or
  1446. modify it under the same terms as Perl itself.
  1447.  
  1448. =cut
  1449.